package simulacao.util.thread;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadEscrita implements Runnable {

    private Queue<String> queue = null;
    private Boolean stop = false;
    BufferedWriter bufferedWriter = null;

    public ThreadEscrita(Queue queue) {
        this.queue = queue;
        try {
            // A linha abaixo salva o log no console
//            bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out,"UTF8"));

            // A linha abaixo salva o log em arquivo texto
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("saida_Simulação.txt"),"UTF8"));

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                synchronized (this) {
                    String s = queue.poll();
                    if (s != null) {
//                        System.out.println("Consumindo -> " + s);
//                        System.out.println(s);
                        bufferedWriter.write(s);
                        bufferedWriter.newLine();
                    }

                    try {
                        this.wait(5);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadEscrita.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    if (stop && queue.isEmpty()) {

//                    System.out.println("Fila consumida por inteiro... Parando Thread...");
                        bufferedWriter.write("Fila consumida por inteiro... Parando Thread...");

                        if (bufferedWriter != null) {
                            bufferedWriter.flush();
                            bufferedWriter.close();
                        }

                        return;
                    }
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(ThreadEscrita.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                } catch (IOException ex) {
                    Logger.getLogger(ThreadEscrita.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }

    }

    public void init() {
        new Thread(this, "ThreadEscrita").start();
    }

    public void stop() {
        this.stop = true;
    }

    public void flush() {
        try {
            bufferedWriter.flush();
        } catch (IOException ex) {
            Logger.getLogger(ThreadEscrita.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
